<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>销售退货订单记</title>
    <script type="text/javascript">
      var editSaleReturnedWin;
      var saleReturnedAssociateAuditWin;
      
      var saleReturnedId;
      var currentOrderNumber;//当前正操作的销售单单号
      Ext.onReady(function(){

        var customerTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<div style="float:left; width:70px">{number}</div>|{name}', '</div></tpl>');
        var customerStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/customer/getAllCustomers?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number',
              convert:function(value,record){
                if (value === ""){
                  return "未设置编号"
                }else{
                  return value;
                }
              }
            }, {
              name: 'name'
            }, {
              name: 'linkman'
            }, {
              name: 'phone'
            }, {
              name: 'address'
            }])
        });

        var customer =  new Ext.form.ComboBox({
          fieldLabel: '客户',
          store: customerStore,
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'customer_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          //pageSize: 10,
          //hideTrigger: false,
          tpl: customerTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true,
          anchor: '95%'
        });
        
        var orderNumber = new Ext.form.TextField({
          fieldLabel: '单号',
          name: 'order_number',
          anchor: '95%'
        });        

        var stateStore = new Ext.data.ArrayStore({
          fields: ['text','value'],
          data : auditStatusArray
        });
        
        var auditingStatus = new Ext.form.ComboBox({
          fieldLabel: '审批状态',
          store: stateStore,
          displayField:'text',
          typeAhead: true,
          mode: 'local',
          name: 'auditing_status',
          forceSelection: true,
          triggerAction: 'all',
          editable:false,
          valueField: 'value',
          emptyText:'',
          selectOnFocus:true,
          anchor: '95%'
        })

        var beginDate = new Ext.form.DateField({
          fieldLabel: '退货日期',
          name: 'begin_date',
          id: 'begin_date',
          format: 'Y-m-d', //格式化日期
          width: '100',
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-01",
          inputType: '2010-01-01',
          anchor: '95%',
          vtype: 'daterange',
          endDateField: 'end_date',
          listeners: {
            select: function(field, e){
              //Ext.MessageBox.alert('提示', '提交成功');
            }
          }
        });
        
        var endDate = new Ext.form.DateField({
          fieldLabel: '至    ',
          name: 'end_date',
          id: 'end_date',
          format: 'Y-m-d', //格式化日期
          width: '100',
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-01",
          inputType: '2010-01-01',
          anchor: '95%',
          vtype: 'daterange',
          startDateField: 'begin_date'
        });

        var submitButton = new Ext.Button({
          text: '搜索',
          iconCls: 'finding',
          handler: function(){
            saleOrderDS.removeAll();
            saleOrderDS.baseParams.order_number = orderNumber.getValue();
            saleOrderDS.baseParams.auditing_status = auditingStatus.getValue();

            saleOrderDS.baseParams.begin_date = beginDate.getRawValue();
            saleOrderDS.baseParams.end_date = endDate.getRawValue();
            saleOrderDS.baseParams.customer_id = customer.getValue();
            saleOrderDS.load();
          }
        });

        var clearButton = new Ext.Button({
          text: '清空',
          width:50,
          handler: function(){
            queryFormPanel.form.reset();
          }
        });

        var queryFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'query_form',
          labelWidth: 65,
          width: screenWidth-175,
          labelAlign: 'right',
          frame : true,
          border:false,
          items: [{
              xtype: 'fieldset',
              defaults: {width: screenWidth-180},
              title: '查询条件',
              border: true,
              items: [{
                  layout: 'column',
                  border: false,
                  items: [{
                      columnWidth: .15,
                      layout: 'form',
                      border: false,
                      items: [orderNumber]
                    }, {
                      columnWidth: .15,
                      layout: 'form',
                      border: false,
                      items: [auditingStatus]
                    }, {
                      columnWidth: .25,
                      layout: 'form',
                      border: false,
                      items: [customer]
                    }]
                },{
                  layout: 'column',
                  border: false,
                  items: [{
                      columnWidth: .15,
                      layout: 'form',
                      border: false,
                      items: [beginDate]
                    }, {
                      columnWidth: .15,
                      layout: 'form',
                      border: false,
                      items: [endDate]
                    }, {
                      columnWidth: .1,
                      layout: 'form',
                      border: false,
                      items: [submitButton]
                    }, {
                      columnWidth: .1,
                      layout: 'form',
                      border: false,
                      items: [clearButton]
                    }]
                }]
            }]
        });
        //显示销售退货订单操作时的窗口介面。
        //----------------------------------销售退货订单Grid-------------------------
        //销售退货订单Grid Store
        var saleReturnedDS = new Ext.data.Store({
          paramNames: {
            start: "start",
            limit: "limit"
          },
          baseParams: {
            start: 0,
            limit: pageSize
          },
          proxy: new Ext.data.HttpProxy({
            url: '/sale_returned/getAllSaleReturneds'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'order_number'
            },{
              name: 'sale_order_number',
              mapping:'sale_order',
              convert:function(value,record){
                if(value == "" || value === null){
                  return "";
                }else{
                  return value.order_number;
                }
              }
            }, {
              name: 'action_date'
            }, {
              name: 'amount',
              type: 'float'
            }, {
              name: 'paid_amount',
              type: 'float'
            }, {
              name: 'description'
            }, {
              name: 'auditing_status'
            }, {
              name: 'associate_audit_opinion'
            },{
              name: 'associate_auditor_name',
              mapping:'associate_auditor',
              convert:function(value,record){
                if(value == ""){
                  return "";
                }else{
                  return value.name;
                }
              }
            }, {
              name: 'customer_name',
              mapping:'customer.name'
            }, {
              name: 'department_name',
              mapping:'department.name'
            }, {
              name: 'employee_name',
              mapping:'employee.name'
            }, {
              name: 'deal_with_status'
            }, {
              name: 'store_status'
            }, {
              name: 'warehouse_employee_name',
              mapping: 'warehouse_employee',
              convert:function(value,record){
                if(value == ""){
                  return "";
                }else{
                  return value.name;
                }
              }
            }, {
              name: 'created_at'
            }, {
              name: 'updated_at',
              type : 'timestamp',
              dateFormat : 'timestamp'
            }])
        });
        
        //生成销售退货订单Grid的CM
        var saleReturnedSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        var saleReturnedCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),saleReturnedSM,{
              id: 'common',
              header: 'DB',
              dataIndex: 'id',
              width: 50
            },{
              header: '销售退货订单单号',
              dataIndex: 'order_number',
              width: 120
            },{
              header: '销售订单单号',
              dataIndex: 'sale_order_number',
              width: 180
            },{
              header: '供应商',
              dataIndex: 'customer_name',
              width: 150
            },{
              header: '总金额',
              dataIndex: 'amount',
              align: 'right',
              width: 75
            },{
              header: '已付金额',
              dataIndex: 'paid_amount',
              align: 'right',
              summaryType: 'sum',
              width: 75
            },{
              header: '退货日期',
              dataIndex: 'action_date',
              renderer: Ext.util.Format.dateRenderer('Y-m-d'),
              width: 70
            },{
              header: '操作员',
              dataIndex: 'employee_name',
              width: 60
            },{
              header: '部门',
              dataIndex: 'department_name',
              width: 70
            },{
              header: '审批状态',
              dataIndex: 'auditing_status',
              width: 60,
              renderer: auditingStatusRender
            },{
              header: '内勤审批者',
              dataIndex: 'associate_auditor_name',
              width: 75
            },{
              header: '内勤审批意见',
              dataIndex: 'associate_audit_opinion',
              width: 150
            },{
              header: '处理状态',
              dataIndex: 'deal_with_status',
              renderer: dealWithStatusRender,
              width: 70
            },{
              header: '入库状态',
              dataIndex: 'store_status',
              renderer: dealWithStatusRender,
              width: 70
            },{
              header: '仓库操作员',
              dataIndex: 'warehouse_employee_name',
              width: 70
            },{
              header: '生成日期',
              dataIndex: 'created_at',
              renderer: Ext.util.Format.dateRenderer('Y-m-d H:i'),
              width: 110
            },{
              header: '修改日期',
              dataIndex: 'updated_at',
              renderer: Ext.util.Format.dateRenderer('Y-m-d H:i'),
              width: 110
            }
          ]});

        //生成要订单的产品的Grid
        var saleReturnedGrid = new Ext.grid.GridPanel({
          title:'销售退货订单列表',
          store: saleReturnedDS,
          cm: saleReturnedCM,
          sm: saleReturnedSM,
          loadMask: true,
          width: screenWidth-175,
          height: 345,
          frame: true,
          //title: '进货品种列表',
          //plain:true,
          //plugins: checkColumn,
          bbar: new Ext.PagingToolbar({
            pageSize: pageSize,
            store: saleReturnedDS,
            displayInfo: true,
            displayMsg: "显示第 {0} 条到 {1} 条记录，一共 {2} 条",
            emptyMsg: "没有记录"
          }),
          tbar: [{
              text: '编辑',
              iconCls: 'editItem',
              handler : function(){
                var records = saleReturnedGrid.getSelectionModel().getSelections();
                if(records.length==0){
                  Ext.MessageBox.show({
                    title: '提示信息',
                    msg: "请先选中一条记录后，再编辑。",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                }else{
                  saleReturnedId = records[0].get('id');
                  if(records[0].get('auditing_status').indexOf('通过') < 0 && records[0].get('auditing_status').indexOf('申请') < 0 ){
                    editSaleReturnedWin = new Ext.Window({
                      layout: 'fit',
                      width: 890,
                      height: 500,
                      closeAction: 'destroy',
                      plain: true,
                      modal: true,
                      constrain:true,
                      //modal: true,
                      title: '编辑销售退货订单',
                      autoLoad: {
                        url: "/sale_returned/editSaleReturned?id="+saleReturnedId,
                        scripts: true,
                        callback: function(options, success, response, request)
                        {
                          if (response.responseText === "NoPrivilege"){
                            editSaleReturnedWin.close();
                          }
                        }
                      }
                    });
                    editSaleReturnedWin.on("destroy",function(){
                      saleReturnedDS.reload();
                    });
                    editSaleReturnedWin.resizable = false;
                    editSaleReturnedWin.show();
                  }else{
                    Ext.Msg.alert('提示信息','正在申请、已经通过审批或已经撤消的销售退货订单，不能编辑。');
                  }
                } 
              }
            },"-",{
              text: '撤消',
              iconCls: 'cancel',
              handler : function(){
                var records = saleReturnedGrid.getSelectionModel().getSelections();
                if (records.length == 0) {
                  return false;
                }else{
                  if(records[0].get('auditing_status').indexOf('申请') < 0 && records[0].get('auditing_status').indexOf('撤消') < 0 ){
                    var orderNumber = records[0].get('order_number')
                    saleReturnedId = records[0].get('id');
                    Ext.MessageBox.confirm("提示","你确认要申请撤消订单号为： \""+orderNumber+"\" 的销售退货订单吗？",function(btn){
                      if(btn=="yes"){
                        Ext.Ajax.request({
                          url : '/sale_returned/applyToCancel?id=' + saleReturnedId,
                          success : function (result, request) {
                            saleReturnedDS.reload();
                          },
                          failure : function (result, request){
                            Ext.MessageBox.show({
                              title: '消息',
                              msg: "通讯失败，请从新操作",
                              buttons: Ext.MessageBox.OK,
                              icon: Ext.MessageBox.WARNING
                            });
                          },
                          method : 'GET'
                        });
                      }else{
                        //alert("no");
                      }
                    });
                  }else{
                    Ext.Msg.alert('提示信息','正处于申请状态的销售退货订单，不能撤消。');
                  }
                }
              }
            }]
        });
        
        //saleReturnedDS.load(privilegeJsonCallBack);
        saleReturnedDS.load();

        saleReturnedGrid.on('rowdblclick', function(gridPanel, rowIndex, e){
          saleReturnedId = saleReturnedDS.getAt(rowIndex).get('id');
          var saleReturnedNumber = saleReturnedDS.getAt(rowIndex).get('order_number');
          //saleReturnedDS.reload();
          saleReturnedDetailDS.removeAll();
          saleReturnedDetailDS.baseParams.sale_returned_id = saleReturnedId;
          saleReturnedDetailDS.load();
          saleReturnedDetailGrid.setTitle("销售退货订单："+saleReturnedNumber+"，的详细信息");
        });
        
        //右键菜单，以弹出此订单相关的入库单
        //右键
        saleReturnedGrid.on('rowcontextmenu', function(grid, rowIndex, e){
          saleReturnedId = saleReturnedDS.getAt(rowIndex).get('id');
          currentOrderNumber = saleReturnedDS.getAt(rowIndex).get('order_number');
          var auditingStatus = saleReturnedDS.getAt(rowIndex).get('auditing_status');
          if (auditingStatus.indexOf("通过") > -1 || auditingStatus=="审批退回"){
            associateAuditItem.setDisabled(true);
          }else {
            associateAuditItem.setDisabled(false);
          }
          e.preventDefault();
          rightClick.showAt(e.getXY());
        });
        //############ 订单-右键菜单 ##########
        var associateAuditItem = new Ext.menu.Item({
          text: '【审批销售退货订单】',
          //iconCls: 'album',
          handler: rightMenuAuditFn
        });

        function rightMenuAuditFn(){
          saleReturnedAssociateAuditWin = new Ext.Window({
            layout: 'fit',
            width: 305,
            height: 190,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            draggable: false,
            //modal: true,
            title: '审批销售退货订单\"'+currentOrderNumber+'\"',
            autoLoad: {
              url: "/sale_returned/associateAuditSaleReturned?id="+saleReturnedId,
              scripts: true
            }
          });
          saleReturnedAssociateAuditWin.on("destroy",function(){
            saleReturnedDS.reload();
          });
          saleReturnedAssociateAuditWin.resizable = false;
          saleReturnedAssociateAuditWin.show();
        }

        
        var rightClick = new Ext.menu.Menu({
          items: [associateAuditItem]
        });


        //--------------------------销售退货订单详细，双击后可显示数据----------------
        //销售退货订单Grid Store Detail
        var saleReturnedDetailDS = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: '/sale_returned/getSaleReturnedDetailsById'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'product_name',
              mapping:'product.name'
            },{
              name: 'product_number',
              mapping:'product.number'
            },{
              name: 'spec',
              mapping:'product.spec'
            },{
              name: 'quantity',
              type: 'int'
            }, {
              name: 'unit_price',
              type: 'float'
            }, {
              name: 'amount',
              type: 'float'
            }, {
              name: 'is_suit',
              mapping:'product.is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }, {
              name: 'description',
              mapping:'product.description'
            }])
        });

        //生成销售退货订单详细表的Grid的CM
        var saleReturnedDetailSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        var saleReturnedDetailCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),saleReturnedDetailSM,{
              id: 'common',
              header: 'DB',
              dataIndex: 'id',
              width: 50
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              width: 230
            },{
              header: '编号',
              dataIndex: 'product_number',
              width: 70
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 80
            },{
              header: '数量',
              align: 'right',
              dataIndex: 'quantity',
              width: 80
            },{
              header: '单价',
              dataIndex: 'unit_price',
              align: 'right',
              renderer: moneyPrivilegeRender,
              width: 70
            },{
              header: '总价',
              dataIndex: 'amount',
              align: 'right',
              renderer: moneyPrivilegeRender,
              width: 70
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            },{
              header: '备注',
              dataIndex: 'description',
              width: 150
            }
          ]});
        //生成要订单的产品的Grid
        var saleReturnedDetailGrid = new Ext.grid.GridPanel({
          title:'订单详细列表',
          store: saleReturnedDetailDS,
          cm: saleReturnedDetailCM,
          sm: saleReturnedDetailSM,
          loadMask: true,
          width: screenWidth-175,
          height: screenHeight-650,
          frame: true
        });

        //总的panel
        var workbenchPanel = new Ext.Panel({
          width: screenWidth-175,
          height: screenHeight-180,
          frame:false,
          layout:'table',
          layoutConfig: {columns:1},
          defaults:{margins:'5 5 5 5'},
          items:[queryFormPanel,saleReturnedGrid,saleReturnedDetailGrid]
        });
        workbenchPanel.render("workbench_panel");
      })
    </script>
  </head>
  <body>
    <div id="workbench_panel"></div>
  </body>
</html>